module LockDown
  module Core
    
    module Users
      def has_user_id?(uid)
        return false unless uid
        user.each{|usr| return true if usr.id == uid}
        return false
      end
    end # end Users module
    
    module SystemObjects
      def has_system_object_id?(obj_id)
        return false unless obj_id
        system_objects.each{|obj| return true if obj.id == obj_id}
        return false
      end

      def add_system_object(sobj)
        return unless sobj
        system_objects << sobj unless has_system_object_id?(sobj.id)
      end

      def delete_system_object(sobj)
        return unless sobj
        system_objects.delete(sobj) unless sobj.nil?
      end

      def delete_all_system_objects
        sobjs = system_objects.dup
        sobjs.each{|sobj| system_objects.delete(sobj)}
      end

      def managed_system_objects
        rvalue = Array.new
        system_objects.each do |sobj|
          next unless sobj.can_remove
          rvalue << sobj
        end
        rvalue
      end      
    end # end SystemObject module
    
    module UserGroups
      def clear_user_group_associations
        user_groups.clear
      end

      def has_user_group_id?(grp_id)
        return false unless grp_id
        user_groups.each{|ug| return true if ug.id == grp_id}
        return false
      end

      def user_group_ids
        ids = Array.new
        rslt = connection.query(user_group_ids_sql)
        rslt.each{|row| ids << row[0].to_i }
        ids
      end
      
      private
        def user_group_ids_sql
          "SELECT user_group_id FROM #{user_groups.options[:join_table]} where #{user_groups.primary_key_name} = #{self.id}"
        end
    end # end UserGroups module
    
  end # end Core module
end # end LockDown module

